/*
 * Copyright 2014 François Rajchenbach.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package qmd.rgo.format;

import java.io.BufferedWriter;
import java.io.IOException;

/**
 * A context object returned by the API when the next step is to add a member to
 * the current JSON object, or to indicate that all members have been defined.
 * 
 * @param <T>
 *            The type of the context object to be returned after the object is
 *            complete
 *
 * @author François Rajchenbach
 * @since 1.0
 */
public final class ObjectContext<T> {

	private final T nextContext;
	private final BufferedWriter writer;
	private boolean empty;

	protected ObjectContext(final T argNextContext,
			final BufferedWriter argWriter) {
		nextContext = argNextContext;
		writer = argWriter;
		empty = true;
	}

	/**
	 * Starts defining a new named entry to the current object.
	 * 
	 * @param argName
	 *            The name of the new entry
	 * @return The context object to set the value of the new entry
	 * @throws IOException
	 *             If an I/O error occurs
	 */
	public ValueContext<ObjectContext<T>> atEntry(final String argName)
			throws IOException {
		if (!empty) {
			writer.write(',');
		}
		empty = false;
		writer.write('"');
		writer.write(argName);
		writer.write('"');
		writer.write(':');
		return new ValueContext<ObjectContext<T>>(this, writer);
	}

	/**
	 * @return The context object after the object is complete
	 * @throws IOException
	 *             If an I/O error occurs
	 */
	public T noMoreEntry() throws IOException {
		writer.write('}');
		return nextContext;
	}

}
